package cn.loioi.multi.service.impl.uesr;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;

import cn.loioi.multi.common.BaseServiceImpl;
import cn.loioi.multi.mysql.been.SysUserMapper;
import cn.loioi.multi.mysql.model.SysUser;
import cn.loioi.multi.service.user.SysUserService;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service("sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserService {
	private @Resource SysUserMapper sysUserMapper;

	@Override
	public int updateByAccount(SysUser record) {
		Example example = new Example(SysUser.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("account", record.getAccount());
		return mapper().updateByExampleSelective(record, example);
	}

	@Override
	public int changPassword(String account, String password, String password_again) {
		if (StringUtils.isEmpty(account)) return -1;
		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(password_again)) return -2;
		if (!password.equals(password_again)) return -3;
		SysUser record = new SysUser();
		record.setAccount(account);
		record.setPassword(DigestUtils.md5Hex(password));
		return updateByAccount(record);
	}

	@Override
	public List<Map<String, Object>> selectUserRole(String account) {
		return mapper().selectUserRole(account);
	}

	@Override
	public int insertRoleResource(String account, JSONArray ids) {
		if (StringUtils.isEmpty(account)) return 0;
		mapper().deleteUserRole(account);
		if (ids == null || ids.size() <= 0) {
			return 0;
		} else {
			return mapper().insertUserRole(account, ids.toArray(new Integer[] {}));
		}
	}

	@Override
	public List<SysUser> selectByName(String name) {
		Example example = new Example(SysUser.class);
		if (StringUtils.isNotEmpty(name)) {
			Criteria criteria = example.createCriteria();
			criteria.andLike("name", "%" + name + "%");
		}
		return mapper().selectByExample(example);
	}

	@Override
	public int insert(SysUser record) {
		record.setCreateTime(new Date());
		return super.insert(record);
	}

	@Override
	public int update(SysUser record) {
		record.setUpdateTime(new Date());
		return super.update(record);
	}

	@Override
	protected SysUserMapper mapper() {
		return sysUserMapper;
	}

	@Override
	protected Class<SysUser> getGenericSuperclass() {
		return SysUser.class;
	}
}
